#pragma once 

#include <iostream>
#include <unistd.h>
#include <string>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

enum{
    SOCK_ERR = 1,
    BIND_ERR,
    LISTEN_ERR,
};

//TODO
static const int g_back = 10;

class Sock
{
public:
    Sock(){}
    ~Sock(){}
public:
    void Socket()
    {
        m_sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(m_sockfd < 0)
        {
            log(FATAL, "create sock error, %s : %d", errno, strerror(errno));
            exit(SOCK_ERR);
        }
        int opt = 1;
        setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR|SO_REUSEPORT, &opt, sizeof(opt));
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(m_sockfd, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            log(FATAL, "bind sock error, %d, %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }

    void Listen()
    {
        if(listen(m_sockfd, g_back) < 0)
        {
            log(FATAL,"listen sock error, %d, %s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
    }

    int Accept(std::string* clientip, uint16_t* clientport)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int sockfd = accept(m_sockfd, (struct sockaddr*)&client, &len);
        if(sockfd < 0)
        {
            log(WARNING, "accept sock error, %d, %s", errno, strerror(errno));
            return -1;
        }
        *clientport = ntohs(client.sin_port);
        char ipstr[64];
        inet_ntop(AF_INET, &client.sin_addr, ipstr, sizeof(ipstr));
        *clientip = ipstr;
        return sockfd; 
    }

    bool Connect(const std::string& ip, uint16_t port)
    {
        struct sockaddr_in client;
        memset(&client, 0, sizeof(client));
        client.sin_family = AF_INET;
        client.sin_port = htons(port);
        client.sin_addr.s_addr = inet_addr(ip.c_str());

        int n = connect(m_sockfd, (struct sockaddr*)&client, sizeof(client));
        if(n == -1) 
        {
            std::cerr << "connect to " << ip << ":" << port << std::endl;
            return false;
        }
        return true;
    }

    void Close()
    {
        close(m_sockfd);
    }

    int Fd()
    {
        return m_sockfd;
    }
private:
    int m_sockfd;
};